<template>
	<div class="admin table-s">
		<div class="mt-2">
			<el-card v-loading="loding" class="mt-2 !border-none" shadow="never">
				<mtable :data="tableList" ref="clearSort" :highlightCurrentRow="false" :type="typeTable"
					:list="options.tableTile" :indexmao="indexmao" :rowtype="true" :bill="false" :operation="true"
					:tableheight="'385'" @handleAdds="handleAdds" @onsortchange="onsortchange"
					:defaultSort="{prop: 'title', order: 'ascending' }" :toolwidth="80">
					<template #tool="{item}">
						<el-table-column v-if="item.display==1" :label="item.name" show-overflow-tooltip
							:prop="item.value" :width="item.width">
							<template #default="{ row }">
								<div v-if="item.name=='名称'">
									<el-input v-if="!mode||disableds=='新增作废单'||disableds=='新增入库单'" v-model="row.title"
										@input="onshowtable(row)" @focus="onfocus" :disabled="disabledshow"
										size="small">
										<template #suffix>
											<el-icon class="el-input__icon">
												<MoreFilled @click="onShowtables(row)" style="cursor: pointer;" />
											</el-icon>
										</template>
									</el-input>
									<p v-else class="fontcolor" style="cursor: pointer;" @click="onDetilPopup(row)">
										{{row.title}}
									</p>
								</div>
								<div v-if="item.name=='报废数量'">
									<div class="flex" v-if="row.category_id!=4&&!mode&&row.category_id!=4">
										<el-input v-if="row.category_id==15&&levelType!=1" v-model="row.unit_length"
											class="flex-1" :clearable="false"  @blur="onquantitying(row)" size="small">
											<template #append>{{row.unit_name_15}}/{{row.unit_name}}</template>
										</el-input>
										<el-select class="flex-1" @change="onquantitying(row)"
											v-if="row.category_id==15&&levelType==1" style="width: 120px"
											v-model="row.unit_length" placeholder="Select" size="small">
											<el-option v-for="item in row.sub" :key="item.unit_length"
												:label="item.unit_length+row.unit_name_15+'/'+row.unit_name+' '+item.quantity+row.unit_name"
												:value="item.unit_length" />
										</el-select>
										<template
											v-if="row.category_id==15&&levelType==1">{{row.unit_name_15}}/{{row.unit_name}}</template>
										<div v-if="row.category_id==15&&levelType!=1"
											style="width: 10px;background-color: #fff;"></div>
										<el-input v-model="row.quantity" class="flex-1" :clearable="false"
											oninput="value = value.replace(/[^\.\d]/g, '')"
											placeholder="请输入正整数数值"
											@blur="row.quantity=test(row.quantity,row.title)?row.quantity:''"
											size="small" >
											<template #append>{{row.unit_name}}</template>
										</el-input>
									</div>
									<div v-else class="fontcolor">
										<div class="flex">
											<div class="flex-1" v-if="row.category_id==15">
												{{row.unit_length}}{{row.unit_name_15}}/{{row.unit_name}}
											</div>
											<div class="flex-1" style="margin-left: 10px;">
												{{row.quantity}}{{row.unit_name}}
											</div>
											<div class="flex-1" v-if="row.category_id==15" style="color: #409eff;">
												{{(row.unit_length*row.quantity).toFixed(2)}}{{row.unit_name_15}}
											</div>
										</div>
									</div>
								</div>
								<div v-if="item.name=='库存数量'&&row.category_id==15&&levelType==1">
									<span v-if="numshow">
										<span><!-- {{booktypefilters(row.sub,row.unit_length)}} -->{{row.quantity_num}}</span>
										<span>{{row.unit_name}}</span>
									</span>
									<span v-else-if="mode">{{row.quantity_num}}{{row.unit_name_15}}</span>
									<span v-else></span>
								</div>
								<div v-if="item.name=='库存数量'&&row.category_id==15&&levelType!=1">
									<span>
										<span>{{row.quantity_num}}</span>
										<span v-if="row.quantity_num">{{row.unit_name_15}}</span>
									</span>
								</div>
								<div v-if="item.name=='库存数量'&&row.category_id!=15">
									<span>{{row.quantity_num}}{{row.unit_name}}</span>
								</div>

								<div v-if="item.name=='回收金额'">
									<div class="is-op-font">{{row.convert_amount||'输入回收金额'}}</div>
									<el-input v-if="!mode" :disabled="mode" placeholder="输入回收金额"
										v-model="row.convert_amount" :clearable="true" size="small"
										oninput="value = value.replace(/[^\.\d]/g, '')"
										@blur="()=>{row.convert_amount=keepTwoDecimalFull(row.convert_amount)}">
										<template v-if="row.convert_amount" #append>元</template>
									</el-input>
									<span v-else>{{row.convert_amount}}元</span>
								</div>
								<div v-if="item.name=='从属设备'">
									<el-button @click="onHovertitles(row)" v-if="row.slave_name" size="small">
										{{row.slave_name}}
									</el-button>
								</div>
								<div v-if="item.name=='物料分类'">
									<span>{{ booktypefilter(row.cate_name,row.category_id) }}</span>
								</div>

								<div v-if="item.name=='分类'">
									<span v-for="(a,b) in row?.cate_name" :key="b">
										<span style="margin-right: 10px;" v-if="row.category_id==a.id">{{a.name}}</span>
									</span>
								</div>
								<div v-if="item.name=='报废原因'">
									<el-input v-if="!mode" v-model="row.scrap_reason" class="flex-1" :clearable="true"
										size="small">
									</el-input>
									<span v-else>{{row.scrap_reason}}</span>

								</div>
								<div v-if="item.name=='报废类型'" @click="onselect">
									<div class="is-op-font">{{onscrap_type(row.scrap_type)||'选择报废类型'}}</div>
									<el-select v-if="!mode" v-model="row.scrap_type" size="small" :disabled="mode"
										placeholder="选择报废类型" @change="changeing">
										<el-option v-for="item in options.listAlling" :key="item.id" :label="item.name"
											:value="item.value" />
									</el-select>
									<span v-else>{{row.scrap_type_name}}</span>
								</div>
								<div v-if="item.name=='责任人'" @click="onselect">
									<div class="is-op-font" v-if="row.person_responsible==''||!row.person_responsible">
										{{'选择责任人'}}
									</div>
									<el-select v-if="!mode" v-model="row.person_responsible" :disabled="mode" multiple
										size="small" placeholder="选择责任人" @change="changeing" :no-data-text="`请先选择报废仓库`">
										<el-option v-for="item in options.getListing" :key="item.id" :label="item.name"
											:value="item.id" />
									</el-select>
									<template v-else>
										<span style="margin-right: 10px;"
											v-for="(item,i) in row.person_responsible_value" :key="item.id">
											<span>
												{{item.name}}
											</span>
										</span>
									</template>
								</div>
							</template>
						</el-table-column>
					</template>
					<template #operation="{row}" v-if="!mode||disableds=='新增作废单'">
						<el-button type="danger" link @click="handleDelete(row)">
							删除
						</el-button>
						<el-button type="primary" link @click="onAddItem(row)">
							添加
						</el-button>
					</template>
				</mtable>
			</el-card>
		</div>
		<el-button v-if="tableList.length==0" class="mt-4" style="width: 100%" @click="onAddItem">
			增加
		</el-button>
	</div>
	<div class="tableing" v-if="showTable">
		<div style="padding:10px">
			<div style="height: 510px;">
				<hovertable :tableLists="tableLists" :popupTitle="popupTitle" @onsuccess="onsuccessing"
					@onSelectionchange="onSelectionchange" @rowClickFunc="rowClickFunc" :typeTable2="typeTable2">
				</hovertable>
			</div>
			<div style="display: flex;justify-content: end;padding-top: 20px;">
				<el-button @click="oncolse">取消</el-button>
				<el-button type="primary" @click="onsum">确认</el-button>
			</div>
		</div>
	</div>
	<div class="tableshow" v-if="tableshow">
		<div style="height: 10px;"></div>
		<mcommodityList @onCancel="tableshow = false" @onsumTable="onsumTable" />
	</div>
	<tableHover v-if="Hovertitles" ref="HovertitleRefs" @success="getLists" @close="Hovertitles = false" />
	<EdittablePopup v-if="showTables" ref="editRefs" :type="typeTable" @success="getOptions"
		@close="showTables=false" />

	<detilPopup :show="DetilPopupShow" :title="DetilPopup" :type="30" :list="DetilPopupList"
		@handleClose="DetilPopupShow=false"></detilPopup>
</template>

<script lang="ts" setup>
	import tableHover from '@/components/table-hovers/index.vue'
	import {
		usePaging
	} from '@/hooks/usePagings'
	import mtable from '@/components/table/index.vue'
	import detilPopup from '@/components/detilPopup.vue'
	import hovertable from './hovertable.vue'
	import feedback from '@/utils/feedback'
	import mcommodityList from './commodityList.vue'
	import {
		adminLists,
		admindetail
	} from '@/api/materials/product'
	import {
		adminListPopup
	} from '@/api/water/list'
	import EdittablePopup from '@/components/settable/index.vue'
	import fontGoBeyond from '@/components/fontGoBeyond/index.vue'
	import {
		adminListss,
		orderDataDelete,
		getList,
		listAll
	} from '@/api/delete/list'
	import {
		tableListing
	} from '@/utils/tableData'
	import {
		getCommonFieldDisplay
	} from '@/api/tools/code'
	import useAppStore from '@/stores/modules/inventory'
	const emit = defineEmits(['onShowtables', 'onfocus'])
	const props = defineProps([
		'warehouse_id',
		'tableName',
		'disableds',
		'type_name',
		'mode',
		'popupTitle',
		'type',
		'levelType',
	])

	const changeing = (val : any) => {

	}
	const DetilPopupList = ref([])
	const dataPopup = (id : any) => {
		admindetail({
			id: id
		}).then((data : any) => {
			DetilPopupList.value = data
		})
	}
	const test = (num,title) => {
		num = num.toString()
		var reg = /^((?!0)\d{1,9})$/
		if (!num.match(reg)) {
			feedback.msgError(`${title}报废数量只允许添加正整数，请重新添加`)
			return false
		} else {
			return true
		}
	}


	const DetilPopup = ref('详情')
	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const onscrap_type = (val : any) => {
		if (val) {
			var line = options.listAlling.map(item => item.value).indexOf(val)
			return options.listAlling[line]?.name
		}

	}
	const keepTwoDecimalFull = (num) => {
		var result = parseFloat(num)
		if (isNaN(result)) {
			return ''
		}
		result = Math.round(num * 100) / 100
		var s_x = result.toString()
		var pos_decimal = s_x.indexOf('.')
		if (pos_decimal < 0) {
			pos_decimal = s_x.length
			s_x += '.'
		}
		while (s_x.length <= pos_decimal + 2) {
			s_x += '0'
		}
		return s_x
	}
	const DetilPopupShow = ref(false)
	const onDetilPopup = (val : any) => {
		dataPopup(val.id)
		DetilPopupShow.value = true
	}

	const userStore = useAppStore()
	const popupTitle = computed(() => userStore.popupTitle)
	const tableList = computed(() => userStore.tableList)
	const indexmao = computed(() => userStore.indexmao)
	const typeing = computed(() => userStore.typeing)
	const numshow = computed(() => userStore.numshow)
	const showTables = ref(false)
	const tableLists = ref([])
	const showTable = ref(false)
	const tableshow = ref(false)
	const HovertitleRefs = shallowRef<InstanceType<typeof tableHover>>()
	const editRefs = shallowRef<InstanceType<typeof EdittablePopup>>()
	const outbound_warehouse_id = computed(() => userStore.warehouse_id)
	const clearSort = shallowRef<InstanceType<typeof tableHover>>()
	const disabledshow = ref(false)
	const Hovertitles = ref(false)
	const tableShowbut = ref(null)
	watch(props, (newValue) => {
		formData.warehouse_id = newValue.warehouse_id
	})
	// 表单数据
	const formData = reactive({
		title: '',
		warehouse_id: '',
		root: '',
		is_order: 1,
		filter_ids: []
	})
	const typeTable = ref('scrap_add')

	watch(outbound_warehouse_id, (newValue : any) => {

		if (newValue) {
			disabledshow.value = false
			ongetList()
		}
	})
	watch(tableList, (newValue : any) => {

		formData.filter_ids = []
		if (newValue) {
			newValue.find((val : any) => {
				if (val.cate_name) {
					if (val.cate_name[0].id == 4) {
						formData.filter_ids.push(val.id)
					}
				}
			})
		}
	}, {
		deep: true
	})
	const onselect = () => {
		if (outbound_warehouse_id.value) {

		} else {
			feedback.msgError(`请先选择作废仓库`)
		}
	}

	const onsortchange = (column : any) => {
		if (column.prop === 'title' && column.order !== null) {
			let arr = []
			tableList.value.map(item => {
				(item.title === null || item.title === '') ? arr.push(item) : arr.unshift(item)
			})
			userStore.tableListdata(arr)
		}
	}
	const onsuccessing = async () => {
		await getLists()
		tableLists.value = []
		tableLists.value = pager.lists
	}


	const handleAdds = async () => {
		showTables.value = true
		await nextTick()
		editRefs.value?.open('add')
	}

	const onHovertitles = async (data : any) => {
		Hovertitles.value = true
		await nextTick()
		HovertitleRefs.value?.open('edit')
		HovertitleRefs.value?.setFormData(data)
	}
	const booktypefilter = (list : any, id : any) => {
		if (list) {
			const obj = list.find((val : any) => val.id == id)
			return obj ? obj.name : null
		}
	}
	const booktypefilters = (list : any, id : any) => {
		if (list) {
			const obj = list.find((val : any) => val.unit_length == id)
			return obj ? obj.quantity : null
		}
	}
	const onquantity = (row : any) => {
		const ss = Math.sign(row.quantity)
		if (ss == -1) {
			feedback.msgError(`请输入正数`)
		} else {
			if (props.type == '入库单') { } else {
				if (row.quantity > parseInt(row.quantity_num) + parseInt(row.quantity)) {
					tableList.value[row.index].quantity = row.quantity_num
					feedback.msgError(`数量不能超出库存数量`)
				}
			}
		}
	}
	const elestval = ref(0)
	const indexval = ref()
	const onquantitying = (row : any) => {
		userStore.tableListAddsings(tableList.value)
		elestval.value = row.quantity_num
		indexval.value = row.index
		if (row.unit_length) {
			userStore.onnumshow(true)
			tableShowbut.value = row.index
		}
	}
	const onfocus = () => {
		if (props.type == '入库单') { } else {
			if (popupTitle.value == '10') {

			} else {
				if (outbound_warehouse_id.value) { } else {
					emit('onfocus')
					feedback.msgError('请先选择作废仓库')
					disabledshow.value = true
				}
			}
		}

	}
	const rowClickFunc = (row : any, ref : any) => {
		ref.toggleRowSelection(row)
	}
	const types = () => {
		return adminListss
	}

	const {
		getLists,
		pager
	} = usePaging({
		fetchFun: types(),
		params: formData
	})
	const oncolse = () => {
		showTable.value = false
		userStore.tableListdatas(tbaleindex.value)
	}
	const tbaleindex = ref('')
	const onsumTable = (val : any) => {
		tableshow.value = false
		options.listall = val
		userStore.tableListAddsing(options.listall, tbaleindex.value)
	}
	const options = reactive({
		listall: [] as any[],
		tableTile: [] as any[],
		tableTiles: [] as any[],
		getListing: [] as any[],
		listAlling: [] as any[],
	})
	const onSelectionchange = (val : any) => {
		options.listall = val
	}
	const loding = ref(true)
	const getOptions = () => {
		getCommonFieldDisplay({
			type: typeTable.value
		}).then((data : any) => {
			options.tableTile = data
			loding.value = false
		})
		listAll({
			key: 'scrapping_type'
		}).then((data : any) => {
			options.listAlling = data
		})
	}
	const ongetList = () => {

		getList({
			warehouse_id: outbound_warehouse_id.value
		}).then((data : any) => {

			options.getListing = data
		})
	}

	const onorderDataDelete = (id : any) => {
		orderDataDelete({
			id: id
		}).then((data : any) => {

		})
	}
	const ontype = (rew : any) => {
		if (props.type_name !== "新增报废单") {
			tbaleindex.value = rew.index
			tableshow.value = true
		} else {
			if (outbound_warehouse_id.value) {
				tbaleindex.value = rew.index
				tableshow.value = true
			} else {
				feedback.msgError('请先选择作废仓库')
			}
		}
	}
	const typeTable2 = ref('search_1')
	const onSetType = () => {
		if (popupTitle.value == 10) {
			typeTable.value = 'add_inventory_10'
			typeTable2.value = 'search_1'
		} else if (popupTitle.value == 20) {
			if (typeing.value == "入库单") {
				typeTable2.value = 'search_1'
				typeTable.value = 'add_inventory_10'
			} else {
				typeTable.value = 'scrap_add'
				typeTable2.value = 'search_2'
			}
		}

	}
	const onShowtables = async (rew : any) => {
		emit('onShowtables')
		setTimeout(() => {
			ontype(rew)
		}, 100)
	}
	const onsum = async () => {
		if (JSON.stringify(options.listall) === '[]') {
			feedback.confirm('请选择商品')
		} else {
			userStore.tableListAddsing(options.listall, tbaleindex.value)
			showTable.value = false
		}

	}
	const onAddItem = (index : any) => {
		const a = Math.floor(Math.random() * (100 - 1) + 1)
		const b = Math.floor(Math.random() * (100 - 1) + 1)
		userStore.tableListAdd({
			product_id: `${a + b}s`,
			title: '',
			typeShow: false,
			quantity: 0,
			total_price: 0,
			cargo_weight: 0
		}, index)
	}
	const onshowtable = async (index : any) => {

		if (outbound_warehouse_id.value) {
			tbaleindex.value = index.index
			formData.title = index.title
			await getLists()
			tableLists.value = []
			tableLists.value = pager.lists
			showTable.value = true
		} else {
			feedback.msgError('请先选择作废仓库')
		}

	}
	const handleDelete = async (index : number) => {
		await feedback.confirm('确定要删除？')
		if (index.order_data_id) {
			onorderDataDelete(index.order_data_id)
		}
		userStore.tableListDel(index.index)
	}
	onMounted(() => {
		onSetType()
		getOptions()
		userStore.tableListdata(tableListing())
	})
</script>
<style scoped lang="scss">
	.is-op-font {
		opacity: 0;
		width: 0;
		height: 0;
	}

	.tableing {
		width: 1250px;
		height: 600px;
		background-color: #fff;
		position: fixed;
		left: 50%;
		top: 50%;
		margin-left: -625px;
		margin-top: -300px;
		z-index: 999;
		padding: 10px;
		border: 1px solid rgba(#333, 0.2);
		border-radius: 5px;
	}

	.tableshow {
		width: 1250px;
		height: 600px;
		background-color: #fff;
		position: fixed;
		border-radius: 5px;
		padding: 10px 20px;
		left: 50%;
		top: 50%;
		margin-left: -625px;
		margin-top: -300px;
		z-index: 999;
		border: 1px solid rgba(#333, 0.2);
	}
</style>
<style scoped lang="scss">
	::v-deep .el-input.is-disabled .el-input__inner {
		background-color: #fff !important;
		color: #666666;
		cursor: not-allowed;
	}

	::v-deep .el-input__inner {
		border: 0;
	}

	::v-deep .el-input.is-disabled .el-input__wrapper {
		background-color: #fff !important;
	}

	::v-deep .el-image__error {
		background-color: #fff !important;
	}

	::v-deep .el-textarea.is-disabled .el-textarea__inner {
		background-color: #fff !important;
		border-color: #fff !important;
		color: #666666;
		cursor: not-allowed;
	}

	.fontcolor {
		color: #666666;
	}

	::v-deep.el-table--large .el-table__cell {
		padding: 7px 0;
	}

	.table-s {
		::v-deep .el-input__wrapper {
			box-shadow: 0 0 0 0px #fff inset;
		}
	}

	::v-deep .el-input-group__append,
	.el-input-group__prepend {
		background-color: #fff;
		box-shadow: none;
		padding: 0 4px;
		white-space: nowrap;
	}

	::v-deep .el-card__body {
		padding: 0;
	}
</style>